package com.yicong.ants.ui.order;

import android.view.View;
import android.widget.CheckBox;

import com.alipay.sdk.app.PayTask;
import com.cchao.simplelib.core.JsonHelper;
import com.cchao.simplelib.core.Router;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.model.event.CommonEvent;
import com.cchao.simplelib.ui.activity.BaseTitleBarActivity;
import com.cchao.simplelib.util.StringHelper;
import com.cchao.simplelib.util.ThreadHelper;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.order.OrderAdapterBean;
import com.yicong.ants.databinding.PayOrder2ActivityBinding;
import com.yicong.ants.manager.PayManager;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.mvp.model.listener.OnCallBackModel;
import com.yicong.ants.wxapi.WXPayEntryActivity;

import java.util.HashMap;
import java.util.Map;

/**
 * 支付订单, 特惠景区
 *
 * @author cchao
 */
public class PayOrderActivity2 extends BaseTitleBarActivity<PayOrder2ActivityBinding> implements View.OnClickListener {
    CheckBox checkWeChat;
    CheckBox checkAliPay;

    OrderAdapterBean mAdapterBean;
    private IWXAPI api;

    @Override
    protected int getLayout() {
        return R.layout.pay_order2_activity;
    }

    @Override
    protected void initEventAndData() {
        api = WXAPIFactory.createWXAPI(this, Constants.WeChatId);
        api.registerApp(Constants.WeChatId);

        setTitleBarVisible(false);
        mDataBind.setClick(this);

        mAdapterBean = JsonHelper.toObject(getIntent().getStringExtra(Constants.Extra.JSON), OrderAdapterBean.class);
        mDataBind.setBean(mAdapterBean);
//        ordersn = getIntent().getStringExtra(Constants.Extra.Ordersn);

        checkWeChat = mDataBind.checkWechat;
        checkAliPay = mDataBind.checkAliPay;
    }

    @Override
    protected void onLoadData() {

    }

    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (event.getCode()) {
            case Constants.Event.Pay_Result_Turn:
                finish();
                break;
        }
    }

    public void setOrderNumber(String orderSn) {
        mDataBind.myOrderNumber.setText(orderSn);
        String type = checkAliPay.isChecked() ? "alipay" : "wechat";

        // price * num
        Map<String, String> params = new HashMap<>();
        params.put("amount", mAdapterBean.getTotalAmount());
        params.put("type", type);
        params.put("method", "app");
        params.put("ordersn", orderSn);
        params.put("subject", mAdapterBean.getProductName());
        params.put("goods_type", mAdapterBean.getGoodsType());

        RxHelper.timerConsumer(500, aLong -> {
            UiHelper.showToast("正在发起付款");
            if (checkWeChat.isChecked()) {
                payWeChatOrder(params);
            } else {
                payAliPayOrder(params);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_pay:
                // 如果是二次支付，立即发起付款
                /*if (StringHelper.isNotEmpty(ordersn)) {
                    setOrderNumber(ordersn);
                    return;
                }*/
                // 初次付款 需要生成订单
                switch (mAdapterBean.getGoodsType()) {
                    case OrderAdapterBean.GoodsType.Card:
                        buildCardOrder();
                        break;
                    case OrderAdapterBean.GoodsType.DiscountScenic:
                    case OrderAdapterBean.GoodsType.TrailPartnerScenic:
                    case OrderAdapterBean.GoodsType.AddedProject:
                    case OrderAdapterBean.GoodsType.AdvanceScenic:
                        buildTicketOrder();
                        break;
                }
                break;
            case R.id.rel_alipay:
                checkAliPay.setChecked(true);
                checkWeChat.setChecked(false);
                break;
            case R.id.rel_wechat:
                checkWeChat.setChecked(true);
                checkAliPay.setChecked(false);
                break;
        }
    }

    public void buildTicketOrder() {
        Map<String, String> params = new HashMap<>();
        params.put("pay_method", checkAliPay.isChecked() ? "1" : "2");
        params.put("scenic_id", mAdapterBean.getScenicId());
        params.put("goods_type", mAdapterBean.getGoodsType());
        params.put("price", mAdapterBean.getTotalAmount());
        params.put("scenic_name", mAdapterBean.getScenicName());
        params.put("project_id", StringHelper.isEmpty(mAdapterBean.getProductId()) ? "null" : mAdapterBean.getProductId());
        params.put("project_name", mAdapterBean.getProductName());
        params.put("num", String.valueOf(mAdapterBean.getMVisitorsInfo().size()));
        params.put("goodsType", String.valueOf(mAdapterBean.getGoodsType()));
        params.put("visit_time", mAdapterBean.getVisitTime() + "");
        params.put("use_discount", mAdapterBean.isCheckDiscount() ? "1" : "0");
        params.put("visitors", JsonHelper.toJson(mAdapterBean.getMVisitorsInfo()));

        showProgress();
        addSubscribe(RetrofitHelper.getApis().submitScenicOrder(params)
            .compose(RxHelper.toMain())
            .subscribe(respBean -> {
                hideProgress();
                if (respBean.isCodeFail()) {
                    showToast(respBean.getMsg());
                    return;
                }
                setOrderNumber(respBean.getData().getOrdersn());
                PayManager.CUR_PAY_CATEGORY = "ticket";
                switch (mAdapterBean.getGoodsType()) {
                    case OrderAdapterBean.GoodsType.AddedProject:
                        PayManager.CUR_PAY_CATEGORY = "addedProject";
                        break;
                }
            }, RxHelper.getErrorTextConsumer(this)));
    }

    public void buildCardOrder() {
        Map<String, String> params = new HashMap<>();
        params.put("pay_method", checkAliPay.isChecked() ? "1" : "2");
        params.put("goods_id", mAdapterBean.getProductId());
        params.put("price", mAdapterBean.getTotalAmount());
        params.put("goods_type", mAdapterBean.getGoodsType());
        params.put("goods_num", "1");

        showProgress();
        addSubscribe(RetrofitHelper.getApis().submitCardOrder(params)
            .compose(RxHelper.toMain())
            .subscribe(respBean -> {
                hideProgress();
                if (respBean.isCodeFail()) {
                    showToast(respBean.getMsg());
                    return;
                }
                setOrderNumber(respBean.getData().getOrdersn());
                PayManager.CUR_PAY_CATEGORY = "card";
            }, RxHelper.getErrorTextConsumer(this)));
    }

    public void payAliPayOrder(Map<String, String> bean) {
        PayManager.getAliPayOrder(bean, (OnCallBackModel<String>) datas -> {
            // thread
            ThreadHelper.execute(() -> {
                PayTask alipay = new PayTask(PayOrderActivity2.this);
                Map<String, String> result = alipay.payV2(datas, true);
                PayManager.waitForAliPay(result, new OnCallBackModel<Boolean>() {
                    @Override
                    public void onSuccess(Boolean datas) {
                        Router.turnTo(PayOrderActivity2.this, WXPayEntryActivity.class)
                            .putExtra(Constants.Extra.Code, datas ? 0 : 1)
                            .start();
                    }

                    @Override
                    public void onFailure(String msg) {
                        showToast(msg);
                    }
                });
            });
        });
    }

    public void payWeChatOrder(Map<String, String> bean) {
/*        PayManager.getWeChatPayOrder(context, bean, (OnCallBackModel<PayReq>) datas -> {
            //
            api.sendReq(datas);
        });*/
    }
}
